package com.apexsoft.aas.service.grpc;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONLexer;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class Int64Value implements GrpcType, ObjectDeserializer, ObjectSerializer {
    private static final String type = "type.googleapis.com/google.protobuf.Int64Value";
    public static final Int64Value instance = new Int64Value();

    @Override
    public String type() {
        return type;
    }

    @Override
    public Long deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        Map<String, Object> data = (Map<String, Object>) parser.parseObject(new HashMap<String, Object>());
        Object value = data.get("value");
        if (value instanceof Long) {
            return (Long) value;
        } else if (value instanceof Integer) {
            return ((Integer) value).longValue();
        } else {
            return (Long) value;
        }
    }

    @Override
    public int getFastMatchToken() {
        return JSONToken.LITERAL_INT;
    }

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeWriter out = serializer.out;
        JSONObject data = new JSONObject();
        data.put("@type", type());
        data.put("value", object);
        out.write(data.toJSONString());
    }
}
